/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.ipo.mm.web.servlets;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;




/**
 *
 * @author Administrator
 */

public class DbReportServlet extends HttpServlet
{


    private String tagreport(String string) {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        return string + calendar.get(calendar.MONTH) + calendar.get(calendar.DAY_OF_MONTH) + calendar.get(calendar.YEAR);
    }

    private void generateXLSOutput(String reportname,JasperPrint jasperPrint,HttpServletResponse resp) throws IOException, JRException {
                 String reportfilename = tagreport(reportname) + ".xls";
                 JExcelApiExporter exporterXLS = new JExcelApiExporter();
                 exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
                    exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
                    exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
                    exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
                    exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, resp.getOutputStream());
                    resp.setHeader("Content-Disposition", "inline;filename=" + reportfilename);
                    resp.setContentType("application/vnd.ms-excel");
                    exporterXLS.exportReport();
}
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
             try {
               String reportFormat = request.getParameter("format");
               String reportName =  request.getParameter("report");
               //Logger.getLogger(getClass().getName()).log(Level.INFO, "Begin");
               if(reportFormat.equals("xls")){
                   HttpSession session = request.getSession();
                   //String reportName = request.getParameter("report");
                   InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("/WEB-INF/reports/"+reportName + ".jasper");
                    ServletContext context = this.getServletConfig().getServletContext();
                    JasperPrint jasperPrint = null;
                    HashMap parameterMap = new HashMap();
                    //parameterMap.put('parayear', new String(selectedyear));
                    try {
                        ServletOutputStream servletOutputStream = response.getOutputStream();
                        //JRDataSource dataSource = createReportDataSource(request, selectedyear, reportName);
                        //JRDataSource dataSource = createReportDataSource(request, selectedyear, reportName);

                        //jasperPrint = JasperFillManager.fillReport(reportStream, new HashMap(), dataSource);
                        jasperPrint = JasperFillManager.fillReport(reportStream,new HashMap());
                        generateXLSOutput(reportName, jasperPrint, response);
                    }
                    catch (Exception e) {}

               }
               HashMap parameterMap = new HashMap();
               parameterMap.put("meetingId", new Integer(72));
               ServletOutputStream servletOutputStream = response.getOutputStream();
               Logger.getLogger(getClass().getName()).log(Level.INFO, "servletOutputStream");
               InputStream reportStream = getServletConfig().getServletContext()
                       .getResourceAsStream("/WEB-INF/reports/"+reportName+".jasper");

               if(reportStream.available()>0) {
                   Logger.getLogger(getClass().getName()).log(Level.INFO, "Report found");
               }
               else{
                    StringWriter stringWriter = new StringWriter();
                    PrintWriter printWriter = new PrintWriter(stringWriter);
                    response.setContentType("text/plain");
                    response.getOutputStream().print(String.format("Report {0} not found",reportName));
               }
               response.setContentType("application/pdf");
               response.addHeader("Content-Disposition","attachment; filename=report.pdf");
               Class.forName("com.mysql.jdbc.Driver");
               Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ipo?user=app_server&password=123456");
               Logger.getLogger(getClass().getName()).log(Level.INFO, "prije JasperRunManager ");
               JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, parameterMap, connection);
               Logger.getLogger(getClass().getName()).log(Level.INFO, "nakon JasperRunManager ");
               servletOutputStream.flush();
               servletOutputStream.close();
               Logger.getLogger(getClass().getName()).log(Level.INFO, "flush close");

           } catch(Exception e) {
              Logger.getLogger(getClass().getName()).log(Level.INFO, "123Exception{0}", e.toString());

           }

        /*
         Connection connection;
        response.setContentType("application/pdf");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("/WEB-INF/reports/meetingReport.jasper");
        if(reportStream.available()>0) {
                Logger.getLogger(getClass().getName()).log(Level.INFO, "/WEB-INF/reports/meetingReport.jasper report found");
               }
        HashMap parameterMap = new HashMap();
        parameterMap.put("meetingId", "72");
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ipo?user=app_server&password=123456");

            byte[] report = JasperRunManager.runReportToPdf(reportStream, parameterMap, connection);
            //JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, parameterMap, connection);
            connection.close();
            response.addHeader("Content-Disposition","attachment; filename=meetingReport.pdf");
            response.setContentLength(report.length);
            servletOutputStream.write(report, 0, report.length);
            servletOutputStream.flush();
            servletOutputStream.close();
        }
        catch (Exception e){
            // display stack trace in the browser
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            response.setContentType("text/plain");
            response.getOutputStream().print(stringWriter.toString());
        }
         */
    }

    	private Locale chooseLocale(String locale)
	{

		LocaleWrapper[] locales =
			new LocaleWrapper[]
			{
				new LocaleWrapper(new Locale("cs", "CZ")),
				new LocaleWrapper(Locale.GERMANY),
				new LocaleWrapper(Locale.US),
				new LocaleWrapper(Locale.FRANCE),
				new LocaleWrapper(new Locale("pt", "PT")),
				new LocaleWrapper(new Locale("ro", "RO")),
				new LocaleWrapper(new Locale("sk", "SK"))
			};

		if(locale.equals("en"))
                {
                    return Locale.ENGLISH;
                }
                else{
                    return new Locale("sr");
                }

	}
}
class LocaleWrapper
{
	Locale locale = null;

	public LocaleWrapper(Locale locale)
	{
		this.locale = locale;
	}

	public Locale getLocale()
	{
		return locale;
	}

    @Override
	public String toString()
	{
		return locale.toString() + " - " + locale.getDisplayName(locale);
	}
}


